module  sdram_refresh(
        input                   clk             ,
        input                   refresh_flag    ,
        output      [ 2:0]      cmd             ,

        output  reg refresh_end_flag
);


/////////////////////命令 ras_n cas_n we_n
parameter       [2:0]       CMD_AUTO_REFRESH    =       3'b001  ;
parameter       [2:0]       CMD_NOP       		=       3'b111  ;

////////////////////状态
reg[4:0] current_state ;
parameter
//空闲
idle_state                                      =       5'b00110,
//自动刷新
Auto_Refresh_64ms_state                         =       5'b01110,
Auto_Refresh_NOP1_state                         =       5'b10110,
Auto_Refresh_NOP2_state                         =       5'b10111,
Auto_Refresh_NOP3_state                         =       5'b11000,
Auto_Refresh_NOP4_state                         =       5'b11001,
Auto_Refresh_NOP5_state                         =       5'b11010,
Auto_Refresh_NOP6_state                         =       5'b11011;


///////////////////其他参数
parameter   REFRESH_CYCLE           =       14'd8192;	    //每64ms执行刷新8192次
reg [13:0]  count_auto_refresh      =       14'd0;		    //计数刷新8192次


///////////////////主程序
always @(posedge clk)//状态机
    begin
		
		case (current_state)

            Auto_Refresh_64ms_state: 
					  begin
                            refresh_end_flag<=1'b0;
							current_state=Auto_Refresh_NOP1_state;
					  end
				
				Auto_Refresh_NOP1_state:				// tRC 60ns.
				begin
                    count_auto_refresh<=count_auto_refresh+1;
					current_state=Auto_Refresh_NOP2_state;
				end
													
				Auto_Refresh_NOP2_state:
				begin
					current_state=Auto_Refresh_NOP3_state;
				end
				
				Auto_Refresh_NOP3_state:
				begin
					current_state=Auto_Refresh_NOP4_state;
				end
				
				Auto_Refresh_NOP4_state:
				begin
					current_state=Auto_Refresh_NOP5_state;			
				end
				
				Auto_Refresh_NOP5_state:
				begin
					current_state=Auto_Refresh_NOP6_state;			
				end
				
                Auto_Refresh_NOP6_state:			 
				begin
					 
					if (count_auto_refresh<REFRESH_CYCLE) 
						current_state=Auto_Refresh_64ms_state;
					else begin
							count_auto_refresh=14'd0;
							refresh_end_flag<=1'b1;
							current_state=idle_state;
						end
				end

            idle_state:
                begin
                if(refresh_flag==1'b1)
                    current_state<=Auto_Refresh_64ms_state;
                else
                    current_state=idle_state;
                end
			default : current_state<=idle_state;
        endcase
    end
    
assign cmd =(current_state==Auto_Refresh_64ms_state)?CMD_AUTO_REFRESH:CMD_NOP;

endmodule











